package cn.imoocc.weather1;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.imooc.weather.DayWeather;
import com.imooc.weather.HourWeather;
import com.imooc.weather.WeatherUtils;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * WeatherUtilsImpl实现了具体的天气预报代码
 */
public class WeatherUtilsImplNew implements WeatherUtils {
    private <T> T getValue(Object map, String path, Class<T> clazz) {
        try {
            OgnlContext context = new OgnlContext();
            context.setRoot(map);
            T value = (T) Ognl.getValue(path, context, context.getRoot());
            return value;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 查询未来24小时天气预报
     * @param appCode 阿里云授权码
     * @param area 查询区域
     * @return HourWeather对象列表，按顺序每小时对应一个HourWeather对象
     */
    public List<HourWeather> w24h(String appCode, String area) {
        List<HourWeather> resultList = new ArrayList<HourWeather>();
        try {
            //新建查询请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .get()
                    .url("https://ali-weather.showapi.com/hour24?area=" + area)
                    .header("Authorization", "APPCODE " + appCode)
                    .build();
            Call call = client.newCall(request);
            Response response = call.execute();
            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create();
            //获取服务器返回数据
            String resBody = response.body().string();
            Map result = gson.fromJson(resBody, new TypeToken<Map>() {
            }.getType());
            //包装为对象集合
            List<Map<String, String>> hourList = this.getValue(result, "showapi_res_body.hourList", ArrayList.class);
            //如果没有找到对应地区天气数据，返回空的List列表
            if(hourList == null || hourList.size() == 0){
                return new ArrayList<HourWeather>();
            }
            for (Map<String, String> hour : hourList) {
                HourWeather hourWeather = new HourWeather();
                hourWeather.setYear(hour.get("time").substring(0, 4));
                hourWeather.setMonth(hour.get("time").substring(4, 6));
                hourWeather.setDay(hour.get("time").substring(6, 8));
                hourWeather.setHour(hour.get("time").substring(8, 10));
                hourWeather.setWindDirection(hour.get("wind_direction"));
                hourWeather.setWindPower(hour.get("wind_power"));
                hourWeather.setWeather(hour.get("weather"));
                hourWeather.setTemperature(hour.get("temperature"));
                resultList.add(hourWeather);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultList;

    }

    public List<DayWeather> w3d(String appCode, String area) {
        List<DayWeather> resultList = new ArrayList<DayWeather>();
        try {
            //新建查询请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .get()
                    .url("https://ali-weather.showapi.com/day15?area=" + area)
                    .header("Authorization", "APPCODE " + appCode)
                    .build();
            Call call = client.newCall(request);
            Response response = call.execute();
            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create();
            //获取服务器返回数据
            String resBody = response.body().string();
            Map result = gson.fromJson(resBody, new TypeToken<Map>() {
            }.getType());
            List<Map<String, String>> dayList = this.getValue(result, "showapi_res_body.dayList", ArrayList.class);
            //如果没有找到对应地区天气数据，返回空的List列表
            if(dayList == null || dayList.isEmpty()){
                return new ArrayList<DayWeather>();
            }
            //包装为对象集合
            for (Map<String, String> day : dayList){
                    DayWeather dayWeather = new DayWeather();
                    dayWeather.setYear(day.get("daytime").substring(0, 4));
                    dayWeather.setMonth(day.get("daytime").substring(4, 6));
                    dayWeather.setDay(day.get("daytime").substring(6, 8));
                    dayWeather.setDayAirTemperature(day.get("day_air_temperature"));
                    dayWeather.setNightAirTemperature(day.get("night_air_temperature"));
                    dayWeather.setDayWeather(day.get("day_weather"));
                    dayWeather.setNightWeather(day.get("night_weather"));
                    dayWeather.setDayWindPower(day.get("day_wind_power"));
                    dayWeather.setNightWindPower(day.get("night_wind_power"));
                    resultList.add(dayWeather);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultList;
    }


    public List<DayWeather> w7d(String appCode, String area) {
        List<DayWeather> resultList = new ArrayList<DayWeather>();
        try {
            //新建查询请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .get()
                    .url("http://saweather.market.alicloudapi.com/area-to-weather?needMoreDay=1&area=" + area)
                    .header("Authorization", "APPCODE " + appCode)
                    .build();
            Call call = client.newCall(request);
            Response response = call.execute();
            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create();
            //获取服务器返回数据
            String resBody = response.body().string();
            Map result = gson.fromJson(resBody, new TypeToken<Map>() {
            }.getType());
            //包装为对象集合
            for (int i = 1; i <= 7; i++) {
                Map<String, String> day = this.getValue(result, "showapi_res_body.f" + i, Map.class);
                //如果没有找到对应地区天气数据，返回空的List列表
                if(day == null ){
                    return new ArrayList<DayWeather>();
                }
                DayWeather dayWeather = new DayWeather();
                dayWeather.setYear(day.get("day").substring(0, 4));
                dayWeather.setMonth(day.get("day").substring(4, 6));
                dayWeather.setDay(day.get("day").substring(6, 8));
                dayWeather.setDayAirTemperature(day.get("day_air_temperature"));
                dayWeather.setNightAirTemperature(day.get("night_air_temperature"));
                dayWeather.setDayWeather(day.get("day_weather"));
                dayWeather.setNightWeather(day.get("night_weather"));
                dayWeather.setDayWindPower(day.get("day_wind_power"));
                dayWeather.setNightWindPower(day.get("night_wind_power"));
                resultList.add(dayWeather);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultList;
    }





    public static void main(String[] args) throws IOException, OgnlException {

        /*List<HourWeather> list1 = new WeatherUtilsImpl().w24h("28a8e0cdea484fdd9cba138a72bc1778", "ASJDLKJASLKD");
        System.out.println(list1);*/
        List<DayWeather> list2 = new WeatherUtilsImplNew().w3d("28a8e0cdea484fdd9cba138a72bc1778", "DASDSADSA");
        System.out.println(list2);
        /*List<DayWeather> list3 = new WeatherUtilsImpl().w7d("28a8e0cdea484fdd9cba138a72bc1778", "杭州");
        System.out.println(list3);*/


    }
}
